﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Configuration;
using System.Xml;
namespace EtalkClient
{
    public partial class Login : Form
    {
        private IPAddress ipaddress;
        private Socket socket;
        IPEndPoint endPoint;
        private int serverProt;
        
        public Login()
        {
            InitializeComponent();
        }
        private bool CheckLogin()
        {
            WebService.EtalkServiceSoapClient soapClient = new EtalkClient.WebService.EtalkServiceSoapClient();
            WebService.ArrayOfAnyType obj = soapClient.UserLogin(txtUserName.Text.Trim(),txtUserPassword.Text.Trim());
            if (obj.Count >0)
            {
                Etalk.Library.ClientUser.LoginedUser = new Etalk.Library.ClientUser { ID = obj[1].ToString(), City=obj[3].ToString(),LoginName = txtUserName.Text, Tel = "", UserName = obj[2].ToString(), UserType = "Agent" };
                return true;
            }
            return false;
        }
        private void cmdComfirm_Click(object sender, EventArgs e)
        {
           
            if(txtUserName.Text.Trim()=="" || txtUserPassword.Text.Trim()=="")
            {
                txtStatus.Text = "请输入完整的用户名和密码";
                return;
            }
            txtStatus.Text = "正在登录...";

            
            if (this.CheckLogin())
            {
                txtStatus.Text = "登录成功,正在建立连接...";
                ConnServer();
            }
            else
            {
                MessageBox.Show("用户名和密码不匹配");
                txtStatus.Text = "用户名和密码不匹配...";
                txtUserPassword.Focus();
            }
        }
        private void CheckUser()
        {
          
            byte[] RecvBuffer = new byte[512];
            int nBytes, nTotalBytes = 0;
            StringBuilder sb = new StringBuilder();
            System.Text.Encoding myE = Encoding.UTF8;

            while ((nBytes=socket.Receive(RecvBuffer, 0, 1024, SocketFlags.None)) > 0)
            {
                nTotalBytes += nBytes;
                sb.Append(myE.GetString(RecvBuffer, 0, nBytes));
            }
            txtStatus.Text = sb.ToString();
        }
        //发送连接请求
        private void ConnServer()
        {
            string gStr = "GET / HTTP/1.1\r\nHost: www.easydp.net \r\nConnection: Close\r\n\r\n";
            string  strData = "LOGIN|代理商|{0}|{1}";
            try
            {
                endPoint = new IPEndPoint(ipaddress, serverProt);
                //Socket 对象
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
               // socket.ReceiveTimeout = 10 * 1000;
                socket.Connect(endPoint);

                byte[] byteArr = Encoding.UTF8.GetBytes(string.Format(strData,txtUserName.Text,txtUserPassword.Text));
                socket.Send(byteArr);
                txtStatus.Text = "连接成功,正在验证帐户...";
                ReceiveMsg();
            }
            catch (Exception ex)
            {
                socket.Close();
                endPoint = null;
                txtStatus.Text = ex.Message;
                MessageBox.Show("未连接到远程服务器,请重试");
            }
        }
        private void ReceiveMsg()
        {
            bool flag = true;
            while (flag)
            {
                if (!socket.Connected)
                    socket.Close();
                byte[] buffer = new byte[512];
                socket.Receive(buffer);
                string msgData = System.Text.Encoding.UTF8.GetString(buffer);
                if(msgData.Contains("成功"))
                {
                     flag = false;
                     new Etalk.Library.Client(txtUserName.Text, socket);
                     
                     this.DialogResult = DialogResult.OK;
                     this.Close();
                     
                }
                else
                {
                    socket.Close();
                    flag = false;
                    txtStatus.Text = msgData;
                }
                
            }
        }
        

        private void Login_Load(object sender, EventArgs e)
        {

            ipaddress = IPAddress.Parse(System.Configuration.ConfigurationManager.AppSettings["ServerIP"]);
            serverProt = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["ServerProt"]);
            this.StartPosition = FormStartPosition.CenterScreen;
        }

        private void cmdCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}